<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { Icon } from '@iconify/vue';
import { useI18n } from 'vue-i18n';
import { useAiTimelineStore } from '../stores/aiTimeline';
import { commandService } from '../services/commandService';

const props = defineProps({
  /** 当前活跃文件路径，用于过滤显示相关的AI变更 */
  activeFilePath: { type: String, default: '' },
  /** 是否显示所有文件的变更，默认只显示当前文件 */
  showAllFiles: { type: Boolean, default: false }
});

const emit = defineEmits(['timeline-item-click', 'accept-change', 'reject-change']);
const { t } = useI18n();

const aiTimeline = useAiTimelineStore();
const selectedEntryId = ref(null);
const showAcceptRejectButtons = ref(true);

// 计算当前显示的AI时间线条目
const displayEntries = computed(() => {
  let entries = aiTimeline.entries.slice().sort((a, b) => b.ts - a.ts);
  
  // 如果指定了活跃文件路径且不显示所有文件，则过滤
  if (props.activeFilePath && !props.showAllFiles) {
    const normalizedActivePath = props.activeFilePath.replace(/[\\\//]/g, '/');
    entries = entries.filter(entry => {
      const entryPath = entry.path.replace(/[\\\//]/g, '/');
      return entryPath === normalizedActivePath;
    });
  }
  
  return entries;
});

// 格式化时间戳
function formatTimestamp(timestamp) {
  const date = new Date(timestamp);
  const now = new Date();
  const diffMs = now - date;
  const diffMins = Math.floor(diffMs / (1000 * 60));
  const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
  
  if (diffMins < 1) return '刚刚';
  if (diffMins < 60) return `${diffMins}分钟前`;
  if (diffHours < 24) return `${diffHours}小时前`;
  if (diffDays < 7) return `${diffDays}天前`;
  
  return date.toLocaleDateString('zh-CN', {
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  });
}

// 获取变更类型的图标和颜色
function getChangeIcon(kind) {
  switch (kind) {
    case 'create': return { icon: 'codicon:add', color: 'text-green-600 dark:text-green-400' };
    case 'edit': return { icon: 'codicon:edit', color: 'text-blue-600 dark:text-blue-400' };
    case 'delete': return { icon: 'codicon:trash', color: 'text-red-600 dark:text-red-400' };
    case 'rename': return { icon: 'codicon:symbol-file', color: 'text-yellow-600 dark:text-yellow-400' };
    default: return { icon: 'codicon:diff', color: 'text-slate-600 dark:text-slate-400' };
  }
}

// 处理时间线条目点击
function handleTimelineItemClick(entry) {
  selectedEntryId.value = entry.id;
  emit('timeline-item-click', entry);
  
  // 打开文件并显示内联diff
  try {
    commandService.execute('file:openPath', { uri: entry.path });
  } catch (error) {
    console.warn('Failed to open file from AI timeline:', error);
  }
}

// 处理接受变更
function handleAcceptChange(entry, event) {
  event.stopPropagation();
  emit('accept-change', entry);
}

// 处理拒绝变更
function handleRejectChange(entry, event) {
  event.stopPropagation();
  emit('reject-change', entry);
}

// 处理全部接受
async function handleAcceptAll() {
  try {
    await aiTimeline.clearTimeline();
    await aiTimeline.loadEntries();
  } catch (error) {
    console.warn('Failed to accept all changes:', error);
  }
}

// 处理全部拒绝
async function handleRejectAll() {
  try {
    const result = await aiTimeline.rollbackAll({ log: false, clear: true });
    if (result.success) {
      await aiTimeline.loadEntries();
    }
  } catch (error) {
    console.warn('Failed to reject all changes:', error);
  }
}

// 刷新时间线
async function refreshTimeline() {
  try {
    await aiTimeline.loadEntries();
  } catch (error) {
    console.warn('Failed to refresh AI timeline:', error);
  }
}

// 组件挂载时加载数据
onMounted(() => {
  refreshTimeline();
});

// 监听活跃文件路径变化
watch(() => props.activeFilePath, () => {
  selectedEntryId.value = null; // 清除选中状态
});
</script>

<template>
  <div class="flex flex-col h-full bg-panel-bg">
    <!-- 头部工具栏 -->
    <div class="flex items-center justify-between px-3 py-2 border-b border-panel-border bg-panel-bg/80">
      <div class="flex items-center gap-2">
        <Icon icon="codicon:timeline" width="16" height="16" class="text-accent" />
        <span class="text-sm font-medium text-app-fg">AI 时间线</span>
        <span class="text-xs text-muted-fg">({{ displayEntries.length }})</span>
      </div>
      
      <div class="flex items-center gap-1">
        <button
          @click="refreshTimeline"
          class="p-1 rounded hover:bg-app-bg text-muted-fg hover:text-app-fg"
          title="刷新时间线"
        >
          <Icon icon="codicon:refresh" width="14" height="14" />
        </button>
        
        <button
          @click="showAcceptRejectButtons = !showAcceptRejectButtons"
          class="p-1 rounded hover:bg-app-bg text-muted-fg hover:text-app-fg"
          :title="showAcceptRejectButtons ? '隐藏操作按钮' : '显示操作按钮'"
        >
          <Icon :icon="showAcceptRejectButtons ? 'codicon:eye-closed' : 'codicon:eye'" width="14" height="14" />
        </button>
      </div>
    </div>

    <!-- 批量操作按钮 -->
    <div v-if="displayEntries.length > 0 && showAcceptRejectButtons" class="flex items-center gap-2 px-3 py-2 border-b border-panel-border bg-panel-bg/50">
      <button
        class="flex-1 px-2 py-1 text-xs rounded bg-[#32CD79] text-white hover:bg-[#2ebd70] dark:bg-[#32CD79] dark:hover:bg-[#2ebd70]"
        @click="handleAcceptAll"
        title="接受所有变更并清空时间线"
      >
        全部接受
      </button>
      
      <button
        @click="handleRejectAll"
        class="flex-1 px-2 py-1 text-xs rounded bg-red-600 text-white hover:bg-red-700 dark:bg-red-500 dark:hover:bg-red-600"
        title="拒绝所有变更并回退修改"
      >
        <Icon icon="codicon:close-all" width="12" height="12" class="inline mr-1" />
        全部拒绝
      </button>
    </div>

    <!-- 时间线条目列表 -->
    <div class="flex-1 overflow-auto">
      <div v-if="displayEntries.length === 0" class="flex flex-col items-center justify-center h-32 text-muted-fg">
        <Icon icon="codicon:timeline" width="24" height="24" class="mb-2 opacity-50" />
        <span class="text-sm">暂无AI变更记录</span>
        <span class="text-xs mt-1">AI编辑文件后会在此显示</span>
      </div>
      
      <div v-else class="space-y-1 p-2">
        <div
          v-for="entry in displayEntries"
          :key="entry.id"
          class="group relative flex flex-col gap-2 p-3 rounded-lg border cursor-pointer transition-all duration-150"
          :class="[
            selectedEntryId === entry.id
              ? 'border-accent bg-accent/10'
              : 'border-panel-border hover:border-accent/50 hover:bg-app-bg/50'
          ]"
          @click="handleTimelineItemClick(entry)"
        >
          <!-- 条目头部信息 -->
          <div class="flex items-start justify-between gap-2">
            <div class="flex items-center gap-2 min-w-0 flex-1">
              <Icon
                :icon="getChangeIcon(entry.kind).icon"
                width="14"
                height="14"
                :class="getChangeIcon(entry.kind).color"
              />
              <div class="min-w-0 flex-1">
                <div class="text-sm font-medium text-app-fg truncate">
                  {{ (entry.kind || 'EDIT').toUpperCase() }}
                  <span class="mx-1 text-muted-fg">·</span>
                  <span class="text-muted-strong">{{ entry.tool || 'AI' }}</span>
                </div>
                <div class="text-xs text-muted-fg truncate" :title="entry.path">
                  {{ entry.path.split(/[\\\/]/).pop() }}
                </div>
              </div>
            </div>
            
            <div class="flex items-center gap-1 text-xs text-muted-fg">
              <span>{{ formatTimestamp(entry.ts) }}</span>
              <span v-if="entry.replacements" class="ml-1 px-1 py-0.5 bg-accent/20 text-accent rounded text-[10px]">
                ×{{ entry.replacements }}
              </span>
            </div>
          </div>

          <!-- 文件路径（如果显示所有文件） -->
          <div v-if="props.showAllFiles" class="text-xs text-muted-fg truncate" :title="entry.path">
            {{ entry.path }}
          </div>

          <!-- 操作按钮 -->
          <div v-if="showAcceptRejectButtons" class="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
            <button
              @click="handleAcceptChange(entry, $event)"
              class="flex-1 px-2 py-1 text-xs rounded bg-green-100 text-green-700 hover:bg-green-200 dark:bg-green-900/30 dark:text-green-400 dark:hover:bg-green-900/50"
              title="接受此变更"
            >
              <Icon icon="codicon:check" width="12" height="12" class="inline mr-1" />
              接受
            </button>
            
            <button
              @click="handleRejectChange(entry, $event)"
              class="flex-1 px-2 py-1 text-xs rounded bg-red-100 text-red-700 hover:bg-red-200 dark:bg-red-900/30 dark:text-red-400 dark:hover:bg-red-900/50"
              title="拒绝此变更"
            >
              <Icon icon="codicon:close" width="12" height="12" class="inline mr-1" />
              拒绝
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 自定义滚动条样式 */
.overflow-auto::-webkit-scrollbar {
  width: 8px;
}

.overflow-auto::-webkit-scrollbar-track {
  background: transparent;
}

.overflow-auto::-webkit-scrollbar-thumb {
  background-color: rgba(100, 116, 139, 0.3);
  border-radius: 4px;
  border: 2px solid transparent;
  background-clip: padding-box;
}

.dark .overflow-auto::-webkit-scrollbar-thumb {
  background-color: rgba(148, 163, 184, 0.3);
}

.overflow-auto::-webkit-scrollbar-thumb:hover {
  background-color: rgba(100, 116, 139, 0.5);
}

.dark .overflow-auto::-webkit-scrollbar-thumb:hover {
  background-color: rgba(148, 163, 184, 0.5);
}
</style>